package org.qh.ai.service.chat.impl;

import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.qh.ai.domain.ChatModel;
import org.qh.ai.domain.vo.ChatModelVo;
import org.qh.ai.enums.ChatModeType;
import org.qh.ai.handler.StreamingChatResponseHandler;
import org.qh.ai.service.request.ChatService;
import org.qh.ai.service.api.IChatModelService;
import org.qh.ai.service.chat.IChatService;
import org.qh.common.ai.entity.chat.Message;
import org.qh.common.ai.entity.request.ChatRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;

/**
 * deepseek
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DeepSeekChatImpl implements IChatService {

    private final IChatModelService chatModelService;
    private final ChatService chatService;

    @Override
    public SseEmitter chat(ChatRequest chatRequest, SseEmitter emitter) {
        ChatModelVo chatModelVo = chatModelService.selectModelByName(chatRequest.getModel());

        ChatModel chatModel = ChatModel.builder()
            .modelName(chatModelVo.getModelName())
            .apiHost(chatModelVo.getApiHost())
            .apiKey(chatModelVo.getApiKey())
            .build();

        try {
            List<Message> messages = chatRequest.getMessages();
            chatService.chat(chatModel, messages, new StreamingChatResponseHandler() {

                @SneakyThrows
                @Override
                public void onPartialResponse(String partialResponse) {
                    emitter.send(partialResponse);
                    log.info("收到消息片段: {}", partialResponse);
                }

                @Override
                public void onCompleteResponse(String completeResponse) {
                    emitter.complete();
                    log.info("消息结束，完整消息: {}", completeResponse);
                }

                @Override
                public void onError(Throwable error) {
                    System.err.println("DeepSeek错误: " + error.getMessage());
                }
            });

        } catch (Exception e) {
            log.error("deepSeek请求失败：{}", e.getMessage());
        }

        return emitter;
    }

    @Override
    public String getCategory() {
        return ChatModeType.DEEPSEEK.getCode();
    }
}
